/*
 * LoginAdmin.java
 *
 * Created on Jan 15, 2011, 1:18:36 PM
 */
package edu.rit.varapp.graphical;

import edu.rit.varapp.utilities.CleanupThread;
import edu.rit.varapp.datalayer.Connect;
import edu.rit.varapp.datalayer.Encryptor;
import edu.rit.varapp.utilities.ExceptionUtils;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 * LoginAdmin is the entry point to the VAR application for an admin. It allows the admin to connect to the database
 * using their username and password. If they are registered as an administrator, it will allow them access to perform
 * various functions on the database. 
 * @author Eric Kisner
 */
public class LoginAdmin extends AbstractView {

    private final Connect connector = new Connect();
    private static final int VIEW_WIDTH = 475;
    private static final int VIEW_HEIGHT = 125;

    /** Creates new form Login */
    public LoginAdmin() {
        super( new Dimension( VIEW_WIDTH, VIEW_HEIGHT ) );
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings( "unchecked" )
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        loginButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        usernameField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        passwordField = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");
        setMinimumSize(new java.awt.Dimension(475, 125));
        setResizable(false);
        getContentPane().setLayout(null);

        jPanel1.setLayout(new java.awt.GridBagLayout());

        loginButton.setText("Login");
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });
        jPanel1.add(loginButton, new java.awt.GridBagConstraints());

        getContentPane().add(jPanel1);
        jPanel1.setBounds(0, 56, 463, 40);

        jPanel2.setLayout(new java.awt.GridLayout(1, 4, 2, 0));

        jLabel1.setText("Username:");
        jPanel2.add(jLabel1);
        jPanel2.add(usernameField);

        jLabel2.setText("Password:");
        jPanel2.add(jLabel2);

        passwordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                passwordFieldKeyPressed(evt);
            }
        });
        jPanel2.add(passwordField);

        getContentPane().add(jPanel2);
        jPanel2.setBounds(10, 10, 450, 30);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
        login();
    }//GEN-LAST:event_loginButtonActionPerformed

    private void passwordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordFieldKeyPressed
        if( evt.getKeyCode() == KeyEvent.VK_ENTER ) {
            login();
        }
    }//GEN-LAST:event_passwordFieldKeyPressed

    private void login() {
        String email = usernameField.getText();
        String password = getPassword();
        boolean isAdmin = false;
        try {
            isAdmin = connector.loginAdmin( email, password );
        } catch( SQLException sqle ) {
            ExceptionUtils.handleException( sqle, this.getClass() );
        }
        if( !isAdmin ) {
            JOptionPane.showMessageDialog( rootPane, "The username/password combination you are trying to login "
                                                     + "with is not registered as a valid administrator. \nPlease "
                                                     + "check that your username and password are correct." );
            resetFields();
            return;
        } else {
            new AdminOperations().setVisible( true );
            this.dispose();
        }
    }

    /**
     * This method returns the entered text in the password field. For additional security, it is recommended to
     * set each character from the returned password text to 0 once retrieved.
     * @return The hashed password that was entered by the user.
     */
    private String getPassword() {
        char[] pwdText = passwordField.getPassword();
        String password = Encryptor.computeHash( new String( pwdText ) );
        for( int i = 0; i < pwdText.length; i++ ) {
            pwdText[i] = 0;
        }
        return password;
    }

    /**
     * Resets all JTextFields when an admin incorrectly enters their username or password, or the username/password
     * is not registered as an administrator.
     */
    private void resetFields() {
        usernameField.setText( "" );
        passwordField.setText( "" );
    }

    /**
     * @param args the command line arguments
     */
    public static void main( String args[] ) {
        java.awt.EventQueue.invokeLater( new Runnable() {

            public void run() {
                new LoginAdmin().setVisible( true );
            }
        } );

        Runtime.getRuntime().addShutdownHook( new CleanupThread() );
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JButton loginButton;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JTextField usernameField;
    // End of variables declaration//GEN-END:variables
}
